﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CuteRibs.D3Armory.Models
{
	public class BNDateTimeConverter : DateTimeConverterBase
	{
		private static readonly DateTime StartDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			return ConvertToDate(Convert.ToInt64(reader.Value));
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			if (!(value is DateTime))
			{
				throw new Exception("Expected date object value.");
			}

			writer.WriteValue(ConvertToSeconds((DateTime)value));
		}

		public static long ConvertToSeconds(DateTime dateTime)
		{
			return Convert.ToInt64((dateTime.ToUniversalTime() - StartDateTime).TotalSeconds);
		}

		public static DateTime ConvertToDate(long seconds)
		{
			return StartDateTime.AddSeconds(seconds).ToLocalTime();
		}
	}
}
